package com.mysteel.product.service.impl;

import com.mysteel.product.entity.SkuImagesEntity;
import com.mysteel.product.entity.SpuInfoDescEntity;
import com.mysteel.product.feign.SecKillFeignService;
import com.mysteel.product.service.*;
import com.mysteel.product.vo.web.SecKillSkuRedisVo;
import com.mysteel.product.vo.web.SkuItemSaleAttrVo;
import com.mysteel.product.vo.web.SkuItemVo;
import com.mysteel.product.vo.web.SpuBaseAttrGroupVo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysteel.common.utils.PageUtils;
import com.mysteel.common.utils.Query;

import com.mysteel.product.dao.SkuInfoDao;
import com.mysteel.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private SecKillFeignService secKillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageOnCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        // key=30&catelogId=225&brandId=14&min=100&max=10000
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(wrapper -> {
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)){
            try {
                BigDecimal maxPrice = new BigDecimal(max);
                if (maxPrice.compareTo(new BigDecimal(0)) == 1){
                    queryWrapper.le("price",max);
                }
            }catch (Exception e){
                log.error("max的值不正确：" + max);
            }

        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("brand_id",brandId);
        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo itemVo = new SkuItemVo();

        // 异步编排
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // 查询sku基本信息
            SkuInfoEntity info = getById(skuId);
            itemVo.setInfo(info);
            return info;
        }, threadPoolExecutor);

        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // sku 销售属性
            List<SkuItemSaleAttrVo> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            itemVo.setSaleAttrs(saleAttrs);
        }, threadPoolExecutor);

        CompletableFuture<Void> descFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // spu介绍信息
            Long spuId = res.getSpuId();
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(spuId);
            itemVo.setSpuDesc(spuInfoDesc);
        }, threadPoolExecutor);

        CompletableFuture<Void> baseAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // spu规格参数信息
            Long catalogId = res.getCatalogId();
            List<SpuBaseAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), catalogId);
            itemVo.setGroupAttrs(groupAttrs);
        }, threadPoolExecutor);


        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            // 查询图片信息
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            itemVo.setImages(images);
        }, threadPoolExecutor);
        // 判断该商品是否在秒杀场次中
        CompletableFuture<Void> skuSecKillFuture = CompletableFuture.runAsync(() -> {
            SecKillSkuRedisVo skuSecKillInfo = secKillFeignService.getSkuSecKillInfo(skuId);
            if (skuSecKillInfo != null) {
                itemVo.setRedisVo(skuSecKillInfo);
            }
        },threadPoolExecutor);


        // 等待所有任务都完成，再返回信息
        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture,skuSecKillFuture).get();

        return itemVo;
    }

}